// 时间戳转化时间格式
export const formatTimestamp: (
  timestamp: string | number,
  format: string
) => string = (timestamp, format = "YYYY-MM-DD HH:mm:ss") => {
  const date = new Date(timestamp);

  if (isNaN(date.getTime())) {
    return "Invalid Date";
  }

  // 位数补齐
  const pad = (num) => num.toString().padStart(2, "0");

  const replacements = {
    YYYY: date.getFullYear(),
    YY: String(date.getFullYear()).slice(-2),
    MM: pad(date.getMonth() + 1),
    M: date.getMonth() + 1,
    DD: pad(date.getDate()),
    D: date.getDate(),
    HH: pad(date.getHours()),
    H: date.getHours(),
    hh: pad(date.getHours() % 12 || 12),
    h: date.getHours() % 12 || 12,
    mm: pad(date.getMinutes()),
    m: date.getMinutes(),
    ss: pad(date.getSeconds()),
    s: date.getSeconds(),
  };

  return format.replace(
    /YYYY|YY|MM|M|DD|D|HH|H|hh|h|mm|m|ss|s/g,
    (match) => replacements[match]
  );
};
